<?php

namespace app\games\controller;

use think\Controller;
use think\Request;
//引入邮箱类
use app\common\library\Email as LibraryEmail;


class User extends Controller
{
    protected $UserModel = null;
    protected $CodeModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->UserModel = model('common/Games/Gameuser');
        $this->CodeModel = model('common/Games/Code');
    }

    // session 验证码
    public function generateCaptcha()
    {
        // 生成随机验证码字符串(数字+字母组合)
        $chars = '0123456789';
        $captchaCode = '';
        $length = 4; // 验证码长度

        for ($i = 0; $i < $length; $i++) {
            $captchaCode .= $chars[mt_rand(0, strlen($chars) - 1)];
        }

        // 生成验证码图片（优化参数：更大的画布和字体）
        $imageWidth = 120;   // 加宽画布
        $imageHeight = 35;   // 加高画布
        $fontSize = 18;      // 显著放大字体（核心调整）

        // 创建画布
        $image = imagecreatetruecolor($imageWidth, $imageHeight);

        // 背景色（稍浅灰色，提升文字对比度）
        $bgColor = imagecolorallocate($image, 245, 245, 245);
        imagefill($image, 0, 0, $bgColor);

        // 文字颜色（深色，确保清晰）
        $textColor = imagecolorallocate($image, mt_rand(30, 80), mt_rand(30, 80), mt_rand(30, 80));

        // 干扰线（减少数量，避免遮挡文字）
        for ($i = 0; $i < 20; $i++) {
            $lineColor = imagecolorallocate($image, mt_rand(180, 220), mt_rand(180, 220), mt_rand(180, 220));
            imageline(
                $image,
                mt_rand(0, $imageWidth),
                mt_rand(0, $imageHeight),
                mt_rand(0, $imageWidth),
                mt_rand(0, $imageHeight),
                $lineColor
            );
        }

        // 干扰点（减少密度，避免遮挡文字）
        for ($i = 0; $i < 90; $i++) {
            $pointColor = imagecolorallocate($image, mt_rand(100, 150), mt_rand(100, 150), mt_rand(100, 150));
            imagesetpixel(
                $image,
                mt_rand(0, $imageWidth),
                mt_rand(0, $imageHeight),
                $pointColor
            );
        }

        // 写入验证码文字（核心优化：精准居中算法）
        // 计算文字水平居中位置（考虑字体宽度和字符数量）
        $textWidth = $fontSize * $length * 0.5; // 估算文字总宽度（0.8是字体宽高比系数）
        $x = ($imageWidth - $textWidth) / 2;

        // 计算文字垂直居中位置（考虑字体基线特性）
        $y = ($imageHeight - $fontSize) / 2; // 0.5是基线补偿值，确保视觉居中

        // 绘制文字（使用imagestring，参数调整为更大字体）
        imagestring($image, 5, $x, $y, $captchaCode, $textColor);
        // 注意：imagestring的第二个参数是字体大小等级（1-5），配合$fontSize变量共同控制大小

        // 保存验证码到session，cofig里面设置了3分钟过期
        session('captcha_code', $captchaCode);

        // 输出图片
        ob_start();
        imagepng($image);
        $imageData = ob_get_clean();
        imagedestroy($image);

        // 返回图片数据
        return json([
            'code' => 1,
            'msg' => '验证码生成成功',
            'data' => [
                'captcha' => 'data:image/png;base64,' . base64_encode($imageData)
            ]
        ]);
    }

    // 注册
    public function register()
    {
        $usernumber = $this->request->param('usernumber', '', 'trim');
        $password = $this->request->param('password', '', 'trim');
        $passwordrequest = $this->request->param('passwordrequest', '', 'trim');
        $code = $this->request->param('code', '', 'trim');

        if (!$usernumber) {
            $this->error('请输入账号');
        }

        if (!$password) {
            $this->error('请输入密码');
        }

        if (!$passwordrequest) {
            $this->error('请输入确认密码');
        }

        if (!$code) {
            $this->error('请输入验证码');
        }

        if ($password != $passwordrequest) {
            $this->error('两次密码不一致');
        }

        if ($code != session('captcha_code')) {
            $this->error('验证码错误');
        } else {
            // 删除验证码
            session('captcha_code', null);
        }

        // 检查账号是否存在
        $userInfo = $this->UserModel->where('usernumber', $usernumber)->find();
        if ($userInfo) {
            $this->error('账号已存在');
        }

        //生成随机盐
        $salt = build_randstr();

        //拼接生成密码
        $password = md5($password . $salt);

        // 插入数据
        $data = [
            'usernumber' => $usernumber,
            'password' => $password,
            'salt' => $salt,
            'username' => build_encrypt($usernumber),
        ];

        // 插入数据
        $res = $this->UserModel->save($data);

        if (!$res) {
            $this->error('注册失败' . $this->UserModel->getError());
        }

        $this->success('注册成功,请重新登录');
    }

    // 登录
    public function login()
    {
        $usernumber = $this->request->param('usernumber', '', 'trim');
        $password = $this->request->param('password', '', 'trim');

        if (!$usernumber) {
            $this->error('请输入账号');
        }

        if (!$password) {
            $this->error('请输入密码');
        }
        // 检查账号是否存在
        $userInfo = $this->UserModel->where('usernumber', $usernumber)->find();
        if (!$userInfo) {
            $this->error('账号不存在');
        }
        // 检查密码是否正确
        if (md5($password . $userInfo['salt']) != $userInfo['password']) {
            $this->error('密码错误');
        }
        // 登录成功
        $this->success('登录成功', '', $userInfo);
    }

    // 发送验证码(登录用)
    public function sendCode()
    {
        if ($this->request->isPost()) {
            $email = $this->request->param('email', '', 'trim');

            if (empty($email)) {
                return $this->error('邮箱不能为空');
            }

            //每次邮箱发过来，都把三十分钟前的删除
            $this->CodeModel->whereTime('createtime', '<', '-30 minutes')->delete();

            $user = $this->UserModel->where('email', $email)->find();

            if (!$user) {
                return $this->error('用户不存在');
            }

            //生成验证码
            $code = build_randstr(6);

            //开启事务
            $this->CodeModel->startTrans();

            //查询邮箱是否已经存在验证码
            $ems = $this->CodeModel->where('email', $email)->find();

            if ($ems) {
                $data = [
                    'id' => $ems['id'],
                    'code' => $code,
                    'times' => bcadd($ems['times'], 1,)
                ];

                if ($ems['times'] > 5 && $ems['ip'] === $this->request->ip()) {
                    //同一账号和ip发送验证次数太多
                    $this->error('验证码发送次数过多，请稍后再试');
                }

                $res = $this->CodeModel->validate('common/Schoolwall/Code.edit')->isUpdate(true)->save($data);
            } else {
                $data = [
                    'email' => $email,
                    'code' => $code,
                    'ip' => $this->request->ip(),
                    'times' => 1,
                ];

                $res = $this->CodeModel->validate('common/Schoolwall/Code')->save($data);
            }

            if ($res === false) {
                $this->error($this->CodeModel->getError() . '请稍后再试');
            }

            //实例化邮箱类
            $Mail = new LibraryEmail();

            //用户接受到的正文
            $html = "您游戏账号证码为：<b>$code</b>";

            //获取发件人
            $FromEmail = config('site.mail_from');

            //发送邮件
            $SendStatus = $Mail->subject('游戏下载认证平台')->from($FromEmail, '游戏下载认证平台')->message($html)->to($email)->send();

            if ($SendStatus === false) {
                //事务回滚
                $this->CodeModel->rollback();

                $this->error($Mail->getError() . '验证码发送失败,请稍后再试');
            } else {
                //确认事务
                $this->CodeModel->commit();
                $this->success('验证码发送成功');
            }
        }
    }

    // 发送验证码(绑定邮箱用)
    public function emailCode()
    {
        if ($this->request->isPost()) {
            $email = $this->request->param('email', '', 'trim');

            if (empty($email)) {
                return $this->error('邮箱不能为空');
            }

            //每次邮箱发过来，都把三十分钟前的删除
            $this->CodeModel->whereTime('createtime', '<', '-30 minutes')->delete();

            $user = $this->UserModel->where('email', $email)->find();

            if ($user) {
                return $this->error('邮箱已被绑定');
            }

            //生成验证码
            $code = build_randstr(6);

            //开启事务
            $this->CodeModel->startTrans();

            //查询邮箱是否已经存在验证码
            $ems = $this->CodeModel->where('email', $email)->find();

            if ($ems) {
                $data = [
                    'id' => $ems['id'],
                    'code' => $code,
                    'times' => bcadd($ems['times'], 1,)
                ];

                if ($ems['times'] > 5 && $ems['ip'] === $this->request->ip()) {
                    //同一账号和ip发送验证次数太多
                    $this->error('验证码发送次数过多，请稍后再试');
                }

                $res = $this->CodeModel->validate('common/Schoolwall/Code.edit')->isUpdate(true)->save($data);
            } else {
                $data = [
                    'email' => $email,
                    'code' => $code,
                    'ip' => $this->request->ip(),
                    'times' => 1,
                ];

                $res = $this->CodeModel->validate('common/Schoolwall/Code')->save($data);
            }

            if ($res === false) {
                $this->error($this->CodeModel->getError() . '请稍后再试');
            }

            //实例化邮箱类
            $Mail = new LibraryEmail();

            //用户接受到的正文
            $html = "您游戏账号证码为：<b>$code</b>";

            //获取发件人
            $FromEmail = config('site.mail_from');

            //发送邮件
            $SendStatus = $Mail->subject('游戏下载认证平台')->from($FromEmail, '游戏下载认证平台')->message($html)->to($email)->send();

            if ($SendStatus === false) {
                //事务回滚
                $this->CodeModel->rollback();

                $this->error($Mail->getError() . '验证码发送失败,请稍后再试');
            } else {
                //确认事务
                $this->CodeModel->commit();
                $this->success('验证码发送成功');
            }
        }
    }

    // 验证码登录
    public function loginCode()
    {
        $email = $this->request->param('email', '', 'trim');
        $code = $this->request->param('code', '', 'trim');

        if (empty($email)) {
            return $this->error('邮箱不能为空');
        }

        if (empty($code)) {
            return $this->error('验证码不能为空');
        }

        $user = $this->UserModel->where('email', $email)->find();

        if (!$user) {
            return $this->error('用户不存在');
        }

        // 检查验证码是否正确
        $codeInfo = $this->CodeModel->where('email', $email)->find();
        if (!$codeInfo) {
            return $this->error('验证码不存在');
        } else {
            if ($codeInfo['code'] != $code) {
                return $this->error('验证码错误');
            }
        }

        // 删除验证码
        $this->CodeModel->where('id', $codeInfo['id'])->delete();
        // 登录成功
        $this->success('登录成功', '', $user);
    }

    // 邮箱绑定
    public function editemail()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $code = $this->request->param('code', '', 'trim');
        }

        $user = $this->UserModel->where('id', $id)->find();
        if (!$user) {
            return $this->error('用户不存在');
        }

        $useremail = $this->UserModel->where('email', $email)->find();
        if ($useremail) {
            return $this->error('该邮箱已被注册');
        }

        $codeinfo = $this->CodeModel->where(['email' => $email, 'code' => $code])->find();
        if (!$codeinfo) {
            return $this->error('验证码错误');
        }

        $user = $this->UserModel->where('id', $id)->update(['email' => $email]);
        if (!$user) {
            return $this->error('绑定失败');
        } else {
            $this->CodeModel->where('id', $codeinfo['id'])->delete();
            return $this->success('绑定成功');
        }
    }

    // 更新登录信息
    public function check()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '', 'trim');

            $user = $this->UserModel->where('id', $id)->find();

            if (!$user) {
                return $this->error('用户不存在');
            }

            $this->success('更新成功', '', $user);
        }
    }

    //修改密码
    public function editpassword()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '', 'trim');
            $requstpassword = $this->request->param('requstPassword', '', 'trim');
            $oldpassword = $this->request->param('oldPassword', '', 'trim');
            $newpassword = $this->request->param('newPassword', '', 'trim');
        }

        if ($requstpassword !== $newpassword) {
            return $this->error('两次密码不一致');
        }

        $user = $this->UserModel->where('id', $id)->find();

        if (!$user) {
            return $this->error('用户不存在');
        }

        if ($user['password'] !== md5($oldpassword . $user['salt'])) {
            return $this->error('旧密码错误');
        }

        $password = md5($newpassword . $user['salt']);

        $res = $this->UserModel->where('id', $id)->update(['password' => $password]);

        if ($res) {
            return $this->success('修改成功');
        } else {
            return $this->error('修改失败');
        }
    }

    // 注销账号
    public function logout()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', 0, 'trim');
            $user = $this->UserModel->where('id', $id)->find();
            if (!$user) {
                return $this->error('用户不存在');
            }
            $this->UserModel->where('id', $id)->delete();
            return $this->success('注销成功');
        }
        return $this->error('注销失败');
    }

    // 更换头像
    public function avatar()
    {
        $params = $this->request->param();
        $id = $this->request->param('id', '', 'trim');

        $user = $this->UserModel->where('id', $id)->find();

        if (!$user) {
            return $this->error("用户不存在");
        }

        //头像认证
        if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {

            $avatar = build_upload('avatar'); //调用build_upload方法,上传头像,对图片进行处理

            if ($avatar['code'] === 0) //code为返回的状态码,为0表示失败,
            {
                $this->error($avatar['msg']); //抛出错误信息
            }

            $params['avatar'] = $avatar['data'];
        }

        $result = $this->UserModel->isUpdate(true)->save($params);

        if ($result === false) //如果返回false,就表示验证失败
        {
            if (isset($params['avatar']) && $_FILES['avatar']['size'] > 0) {
                is_file('.' . $params['avatar']) && unlink('.' . $params['avatar']); //判断上传的文件是否存在,如果存在,就删除上传的文件
            }
            $this->error($this->UserModel->getError()); //抛出错误信息
        } else {
            if (isset($params['avatar']) && $_FILES['avatar']['size'] > 0) {
                is_file('.' . $user['avatar']) && unlink('.' . $user['avatar']);
            }
            $this->success('更新头像成功');
        }
    }

    // 更改昵称
    public function editusername()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', 0, 'trim');
            $username = $this->request->param('username', '', 'trim');

            $bisiness = $this->UserModel->where('id', $id)->find();
            if (!$bisiness) {
                return $this->error('用户不存在');
            }

            if (!$username) {
                return $this->error('新昵称不能与老昵称相同或者为空');
            }

            $res = $this->UserModel->where('id', $id)->update(['username' => $username]);
            if (!$res) {
                return $this->error('更新失败');
            } else {
                return $this->success('更新成功');
            }
        }
    }
}
